package dup.login.demo.controller;

import dup.login.demo.util.RequestUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;

@Controller
public class LoginController {
    @GetMapping("/login")
    public String userLogin() {
        return "user/login";
    }

    @GetMapping("/user/index")
    @ResponseBody
    public String userIndex(HttpServletRequest request) {
        return request.getUserPrincipal().getName();
    }

    @PostMapping("/test")
    @ResponseBody
    public Object Test(HttpServletRequest request) {
        String authorizeUrl = "http://localhost:8888/oauth/token";

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("username", "user1");
        params.add("password", "123456");
        params.add("grant_type", "password");
        params.add("client_id", "demoApp1");
        params.add("client_secret", "demoAppSecret");
        Object req = RequestUtil.sendPostRequest(authorizeUrl, params);

        LinkedHashMap infoMap = (LinkedHashMap) req;
        return infoMap.get("access_token");
    }
}
